package org.example.backend.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.backend.common.Result;
import org.example.backend.entity.Cart;
import org.example.backend.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 购物车控制器
 */
@RestController
@RequestMapping("/cart")
@Api(tags = "购物车接口")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 获取当前用户的购物车列表
     *
     * @param request 请求
     * @return 购物车列表
     */
    @GetMapping("/list")
    @ApiOperation("获取购物车列表")
    public Result<List<Cart>> list(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        return Result.success(cartService.listByUserId(userId));
    }

    /**
     * 添加商品到购物车
     *
     * @param cart    购物车信息
     * @param request 请求
     * @return 添加结果
     */
    @PostMapping("/add")
    @ApiOperation("添加商品到购物车")
    public Result<?> add(@Valid @RequestBody Cart cart, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        cart.setUserId(userId);
        try {
            cartService.addToCart(cart);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     *
     * @param id       购物车ID
     * @param quantity 数量
     * @return 更新结果
     */
    @PutMapping("/update/{id}")
    @ApiOperation("更新购物车商品数量")
    public Result<?> update(@PathVariable Long id, @RequestParam Integer quantity) {
        try {
            cartService.updateQuantity(id, quantity);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除购物车商品
     *
     * @param id 购物车ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除购物车商品")
    public Result<?> delete(@PathVariable Long id) {
        cartService.removeFromCart(id);
        return Result.success();
    }

    /**
     * 清空购物车
     *
     * @param request 请求
     * @return 清空结果
     */
    @DeleteMapping("/clear")
    @ApiOperation("清空购物车")
    public Result<?> clear(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        cartService.clearCart(userId);
        return Result.success();
    }
} 